﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Reflection;

namespace Idlesoft.Utils
{

	

	public static class EnumExtensions
	{
		public static bool And(this Enum e1, Enum e2)
		{
			int i1 = Convert.ToInt32(e1);
			int i2 = Convert.ToInt32(e2);
			return (i1 & i2) > 0;
		}
		public static bool Or(this Enum e1, Enum e2)
		{
			int i1 = Convert.ToInt32(e1);
			int i2 = Convert.ToInt32(e2);
			return (i1 | i2) > 0;
		}
		public static IDictionary<string, int> ToDictionary(this Enum enumeration)
		{
			int value = (int)(object)enumeration;
			return Enum.GetValues(enumeration.GetType()).OfType<int>().Where(v => (v & value) == value).ToDictionary(v => Enum.GetName(enumeration.GetType(), v));
		}
		public static IEnumerable<Enum> GetFlags(this Enum e)
		{
			return Enum.GetValues(e.GetType()).Cast<Enum>().Where(flag => e.HasFlag(flag));
		}

		public static string EnumToString(this Enum e)
		{
			return (e != null) ? e.GetType().FullName + "." + Enum.GetName(e.GetType(), e) : null;
		}

		public static Enum StringToEnum(this string text)
		{
			Enum result = null;
			var match = Regex.Match(text, @"(.+)(\.)(.+)");

			if (match.Groups.Count == 4)
			{
				string type = match.Groups[1].Value;
				string value = match.Groups[3].Value;
				Type enumType = Assembly.GetCallingAssembly().GetType(type);
				foreach (Enum v in Enum.GetValues(enumType))
				{
					if (EnumToString(v) == type + "." + value)
					{
						result = v;
						break;
					}
				}
			}
			return result;
		}
	}
}
